/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ManGasto.java
 *
 * Created on 22/01/2011, 10:42:25
 */
package com.catosist.run.application.viaje.gasto;

import com.catosist.run.application.Util.MiModelo;
import com.catosist.run.business.gestorgasto.GestorGasto;
import com.catosist.run.business.gestorviaje.GestorViaje;
import com.catosist.run.services.GastoDTO;
import com.catosist.run.services.ViajeDTO;
import java.util.Iterator;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.table.DefaultTableModel;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 *
 * @author bicho
 */
public class ManGasto extends javax.swing.JFrame {

    /** Creates new form ManGasto */
    public ManGasto() {
        initComponents();
        refresh();
    }

    public ManGasto(boolean iniciar) {
        initComponents();
        viajeId = 56;
        iniciar();
        refresh();
    }

    public ManGasto(int viajeId, GestorViaje gestorViaje) {
        initComponents();
        this.viajeId = viajeId;
        this.gestorViaje = gestorViaje;
        iniciar();
        refresh();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        lblTitle = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTable2 = new javax.swing.JTable();
        btnAgregar = new javax.swing.JButton();
        btnEditar = new javax.swing.JButton();
        btnEliminar = new javax.swing.JButton();
        lblTotal = new javax.swing.JLabel();
        lblDeuda = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jPanel1.setName("jPanel1"); // NOI18N

        lblTitle.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        lblTitle.setText("jLabel1");
        lblTitle.setName("lblTitle"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jTable1.setName("jTable1"); // NOI18N
        jScrollPane1.setViewportView(jTable1);

        jScrollPane2.setName("jScrollPane1"); // NOI18N

        jTable2.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jTable2.setName("jTable1"); // NOI18N
        jScrollPane2.setViewportView(jTable2);

        btnAgregar.setMnemonic('n');
        btnAgregar.setText("Nuevo gasto");
        btnAgregar.setName("btnAgregar"); // NOI18N
        btnAgregar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAgregarActionPerformed(evt);
            }
        });

        btnEditar.setText("Editar gasto seleccionado");
        btnEditar.setName("btnEditar"); // NOI18N
        btnEditar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEditarActionPerformed(evt);
            }
        });

        btnEliminar.setText("Eliminar gasto seleccionado");
        btnEliminar.setName("btnEliminar"); // NOI18N
        btnEliminar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEliminarActionPerformed(evt);
            }
        });

        lblTotal.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        lblTotal.setText("Total: ");
        lblTotal.setName("lblTotal"); // NOI18N

        lblDeuda.setFont(new java.awt.Font("Dialog", 0, 13));
        lblDeuda.setText("Deuda:");
        lblDeuda.setName("lblDeuda"); // NOI18N

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(lblTitle, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 913, Short.MAX_VALUE)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 913, Short.MAX_VALUE)
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                                .addComponent(btnAgregar)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(btnEditar)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btnEliminar)))
                        .addContainerGap())
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lblTotal)
                            .addComponent(lblDeuda))
                        .addGap(167, 167, 167))))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lblTitle, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnAgregar)
                    .addComponent(btnEditar)
                    .addComponent(btnEliminar))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 414, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(lblTotal)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(lblDeuda)
                .addGap(18, 18, 18))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnAgregarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAgregarActionPerformed
        // TODO add your handling code here:s
        DialogGasto dialogGasto = new DialogGasto(this, true, viajeId, 0);
        dialogGasto.setLocationRelativeTo(this);
        dialogGasto.setVisible(true);
        refresh();
}//GEN-LAST:event_btnAgregarActionPerformed

    private void btnEditarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEditarActionPerformed
        try {
//            int i = this.jTable1.getSelectedRow();
//            i = gestorGasto.getIdAtIndex(i);
            int i = Integer.parseInt(this.jTable1.getValueAt(this.jTable1.getSelectedRow(),0).toString());
            if (i == 0) {
                throw new Exception();
            }
            DialogGasto dialogGasto = new DialogGasto(this, true, viajeId, i);
            dialogGasto.setLocationRelativeTo(this);
            dialogGasto.setVisible(true);
            refresh();
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "Debe seleccionar un gasto existente", "Advertencia", JOptionPane.WARNING_MESSAGE);
        }
    }//GEN-LAST:event_btnEditarActionPerformed

    private void btnEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEliminarActionPerformed
        try {
            int i = Integer.parseInt(this.jTable1.getValueAt(this.jTable1.getSelectedRow(),0).toString());
            //i = gestorGasto.getIdAtIndex(i);
//            if (i == 0) {
////                throw new Exception();
//            }
            int result = JOptionPane.showConfirmDialog(this, "Realmente desea eliminar el gasto seleccionado?", "Eliminar Gasto", JOptionPane.YES_NO_OPTION);
            if (result == JOptionPane.YES_OPTION) {
                gestorGasto.deleteById(i);
                refresh();
            }

        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "Debe seleccionar un gasto existente", "Advertencia", JOptionPane.WARNING_MESSAGE);
        }
    }//GEN-LAST:event_btnEliminarActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
//                new ManGasto().setVisible(true);
                ManGasto manGasto = new ManGasto(true);
                manGasto.setVisible(true);
            }
        });
    }

    private void iniciar() {
        ctx = new ClassPathXmlApplicationContext("/applicationContext.xml");
        gestorGasto = (GestorGasto) ctx.getBean("gestorGasto");
        // gestorViaje = (GestorViaje) ctx.getBean("gestorViaje");
    }

    public int getSelected() {
        return this.jTable1.getSelectedColumnCount();


    }

    public JPanel getPanel() {
        return this.jPanel1;
    }

    private void refresh() {


        ViajeDTO viajeDTO = gestorViaje.getById(viajeId);

        this.lblTitle.setText("Gastos del viaje:     fecha: " + viajeDTO.getFingreso()
                + "             Ruta: " + viajeDTO.getnRuta()
                + "             Chofer: " + viajeDTO.getnPersona()
                + "             Adelanto: " + viajeDTO.getAdelanto());

        DefaultTableModel model = new MiModelo();
        model.addColumn("Id");
        model.addColumn("N.Comprobate");
        model.addColumn("Fecha");
        model.addColumn("Empresa");
        model.addColumn("Descripcion");
        model.addColumn("Tipo");
        model.addColumn("Total");
//        model.addColumn("cantidad");
//        model.addColumn("Precio");

        float total = 0f;
        float adelanto = viajeDTO.getAdelanto();
        List<GastoDTO> gastoDTOs = gestorGasto.getByViajeId(viajeId);
        for (Iterator<GastoDTO> it = gastoDTOs.iterator(); it.hasNext();) {
            GastoDTO gastoDTO = it.next();
            model.addRow(gastoDTO.toArray());
            total += gastoDTO.getTotal();
//            descuentos += gastoDTO.getade
        }
        this.jTable1.setModel(model);

        
        viajeDTO.setTotalgasto(total);
        
        gestorViaje.saveOrUpdate(viajeDTO, viajeId);

        this.lblTotal.setText("Total de gastos: " +String.valueOf(total));
        float deuda = total - adelanto;
        if (deuda > 0) {
            lblDeuda.setText("Monto faltente: " + String.valueOf(deuda));

        }
        else
            if (deuda <= 0) {
                lblDeuda.setText("Mondo a devolver: " + String.valueOf(-1 * deuda));
            }

//        this.jTable1.getColumnModel().getColumn(3).setPreferredWidth(400);
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAgregar;
    private javax.swing.JButton btnEditar;
    private javax.swing.JButton btnEliminar;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable jTable1;
    private javax.swing.JTable jTable2;
    private javax.swing.JLabel lblDeuda;
    private javax.swing.JLabel lblTitle;
    private javax.swing.JLabel lblTotal;
    // End of variables declaration//GEN-END:variables
    private GestorGasto gestorGasto;
    private GestorViaje gestorViaje;
    private int viajeId;
    ApplicationContext ctx;
}
